<?php
/**
 * @APP@
 *
 * PHP versions 5
 *
 * @category   BEAR
 * @package    App
 * @subpackage App_Acl
 * @author     $Author: anonymous $ <anonymous@example.com>
 * @version    SVN: Release: $Id:$
 */

/**
 * 認証
 *
 * Zend_Acl_Role_Interfaceを実装しアクセスのロールを設定できます。
 *
 * @category   BEAR
 * @package    App
 * @subpackage App_Acl
 * @author     $Author: anonymous $ <anonymous@example.com>
 * @copyright  anonymous All rights reserved.
 * @version    SVN: Release: $Id:$
 */
class App_Auth extends BEAR_Base implements Zend_Acl_Role_Interface
{

    /**
     * 認証変数
     *
     * @var array
     */
    private $_auth = null;

    /**
     *
     *
     * @var App_Auth_Adapte
     */
    private $_adapter = array();

    /**
     * リソースユーザーID
     *
     * @var string
     */
    private $_user_id = null;

    public function __construct(array $config)
    {
        parent::__construct($config);
    }

    /**
     * Injector
     *
     * @return void
     */
    public function onInject()
    {
        $this->_adapter = $this->_config;
        $this->_session = BEAR::dependency('BEAR_Session');
        $this->_auth = $this->_session->get('auth');
        $this->_log = BEAR::dependency('BEAR_Log');
    }

    /**
     * LDAP authサンプル（未実装）
     *
     * @return boid
     */
    public function onInjectLdap()
    {
        $this->_adapter = BEAR::dependency('App_Auth_Adapter_Ldap', $this->_config);
    }

    /**
     * ログイン
     * @param array $config
     *
     * @required id
     * @required passowrd
     *
     * @return unknown_type
     */
    public function login(array $config)
    {
        $authAdapter = BEAR::dependency('App_Auth_Adapter_Resource', $config);
        $authResult = $authAdapter->authenticate($authAdapter);
        if ($authResult->isValid()) {
            $identity = $authResult->getIdentity();
            $this->_session->set('auth', $identity);
        }
        return $authResult;
    }

    /**
     * ログアウト
     *
     * @return void
     */
    public function logout()
    {
        $this->_session->unregister('auth');
        $this->_log->log('logout');
    }

    /**
     *  ログイン情報を取得
     *
     * @return array
     */
    public function get()
    {
        return $this->_auth;
    }

    /**
     * ページのユーザーIDをセット
     *
     * @param $userId
     *
     * @return void
     */
    public function setUserId($userId)
    {
        $this->_user_id = $userId;
    }

    /**
     * ロールIDを返す
     *
     * @return string
     */
    public function getRoleId()
    {
        if (!$this->_auth) {
            return 'guest';
        } elseif ($this->_user_id === $this->_auth['id']) {
            return 'owner';
        } else {
            return 'member';
        }
    }
}